<?php

/**
 * Description of DefaultController
 *
 * @author Poh Nean
 */
class DefaultController extends PsController
{

	public function accessRules()
	{
		return CMap::mergeArray(array(
					array('allow',
						'roles' => array('Tickets.Manage'),
					)), parent::accessRules());
	}

	public function actionIndex($ticket_status = 'Open')
	{
		$ticket = new Ticket('search');
		$ticket->unsetAttributes();
		$ticket->current_status = $ticket_status;

		if (isset($_GET['Ticket'])) {
			$ticket->attributes = $_GET['Ticket'];
			$ticket->agency_id = Yii::app()->user->model->agency_id;
		}

		$data = array();
		$data['ticket'] = $ticket;
		$data['ticket_status'] = $ticket_status;
		$data['ticketStatusTypes'] = TicketStatusType::model()->findAll(array('order' => 'is_closing_status ASC'));

		$this->render('index', $data);
	}

	public function actionView($ticket_number)
	{
		$ticket = $this->loadTicket($ticket_number);

		$newTicketResponse = new TicketResponse;

		if (isset($_POST['TicketResponse'])) {
			$newTicketResponse->ticket_id = $ticket->id;
			$newTicketResponse->responded_by_user_id = Yii::app()->user->id;
			$newTicketResponse->agency_id = Yii::app()->user->model->agency_id;
			$newTicketResponse->response_time = new CDbExpression('UTC_TIMESTAMP()');
			$newTicketResponse->attributes = $_POST['TicketResponse'];

			if ($newTicketResponse->validate()) {
				$tx = Yii::app()->db->beginTransaction();
				try {
					if (isset($_POST['Ticket'])) {
						$oldStatus = $ticket->current_status;

						if ($_POST['alsoChangeStatus'] == 1) {
							$ticket->current_status = $_POST['Ticket']['current_status'];
							if ($ticket->current_status != $oldStatus) {
								$ticketStatus = new TicketStatus;
								$ticketStatus->type = $ticket->current_status;
								$ticketStatus->ticket_id = $ticket->id;
								$ticketStatus->status_time = new CDbExpression('UTC_TIMESTAMP()');
								$ticketStatus->changed_by_user_id = Yii::app()->user->id;
								$ticketStatus->save(false);
							}

							$ticket->save(false);
						}
					}

					$newTicketResponse->save(false);
					
					$ticket->sendNotificationEmail(Ticket::NOTIFICATION_TYPE_UPDATED, array('response' => $newTicketResponse->message));

					$tx->commit();

					$this->refresh();
				} catch (CDbException $e) {
					$tx->rollback();
				}
			}
		}

		$data = array();
		$data['ticket'] = $ticket;
		$data['escalation'] = new Escalation;
		$data['ticketEscalationLevels'] = $ticket->getEscalationLevelsListData();
		$data['newTicketResponse'] = $newTicketResponse;
		$this->render('view', $data);
	}

	public function actionCreate()
	{
		$ticket = new Ticket;

		if (isset($_POST['Ticket'])) {
			$ticket->agency_id = Yii::app()->user->model->agency_id;
			$ticket->created_by_user_id = Yii::app()->user->id;
			$ticket->attributes = $_POST['Ticket'];

			$isValid = $ticket->validate();
			if ($isValid) {
				$tx = Yii::app()->db->beginTransaction();

				try {
					$ticket->save(false);

					$ticketStatus = new TicketStatus;
					$ticketStatus->type = 'Open';
					$ticketStatus->ticket_id = $ticket->id;
					$ticketStatus->status_time = new CDbExpression('UTC_TIMESTAMP()');
					$ticketStatus->changed_by_user_id = Yii::app()->user->id;
					$ticketStatus->save(false);
					
					$tx->commit();
					
					$ticket->sendNotificationEmail(Ticket::NOTIFICATION_TYPE_NEW);

					$this->redirect(array('default/index'));
					PsSystemMessage::add('Ticket submitted.', 'success');
				} catch (CDbException $e) {
					$tx->rollback();
				}
			} else {
//				dump($ticket->getErrors());
			}
		}

		$data = array();
		$data['ticket'] = $ticket;
		$this->render('create', $data);
	}

	public function actionUpdate($ticket_number)
	{
		$ticket = $this->loadTicket($ticket_number);
		$oldStatus = $ticket->current_status;

		if (isset($_POST['Ticket'])) {
			$ticket->attributes = $_POST['Ticket'];
			$isValid = $ticket->validate();

			if ($isValid) {
				$tx = Yii::app()->db->beginTransaction();

				try {
					if ($ticket->current_status != $oldStatus) {
						// record ticket history
						$ticketStatus = new TicketStatus;
						$ticketStatus->type = $ticket->current_status;
						$ticketStatus->ticket_id = $ticket->id;
						$ticketStatus->status_time = new CDbExpression('UTC_TIMESTAMP()');
						$ticketStatus->changed_by_user_id = Yii::app()->user->id;
						$ticketStatus->save(false);
					}
					
					$ticket->save(false);

					$tx->commit();

					$this->redirect(array('default/index'));
					PsSystemMessage::add('Ticket updated.', 'success');
				} catch (CDbException $e) {
					$tx->rollback();
				}
			} else {
				
			}
		}
		
		$data = array();
		$data['ticket'] = $ticket;
		$this->render('update', $data);
	}

	public function actionEscalate($ticket_number)
	{
		$ticket = $this->loadTicket($ticket_number);
		if (isset($_POST['Escalation'])) {
			$escalationLevel = $this->loadEscalationLevel($_POST['Escalation']['escalation_level']);
			
			
			$escalation = new Escalation;
			$escalation->attributes = $_POST['Escalation'];
			
			$escalation->ticket_id = $ticket->id;
			$escalation->escalation_time = new CDbExpression('UTC_TIMESTAMP()');
			$escalation->escalated_to_user_id = $escalationLevel->user_id;
			
			if ($escalation->save()) {
				PsSystemMessage::add('Ticket #' . $ticket->ticket_number . ' escalated (Level ' . $escalation->escalation_level . ')', 'success');
			} else {
				PsSystemMessage::add('Error escalating ticket #' . $ticket->ticket_number, 'error');
			}
			
			$this->redirect(array('default/view', 'ticket_number' => $ticket_number));
		}
	}

	public function loadTicket($ticket_number)
	{
		$ticket = Ticket::model()->ownedByCurrentAgency()->findByAttributes(array('ticket_number' => $ticket_number));

		if ($ticket == null) {
			throw new PsPageNotFoundException();
		}

		return $ticket;
	}
	
	/**
	 * @param int $level
	 * @return EscalationLevel
	 * @throws PsPageNotFoundException
	 */
	public function loadEscalationLevel($level) {
		$escalationLevel = EscalationLevel::model()->ofCurrentAgency()->findByAttributes(array('level' => $level));
		
		if ($escalationLevel === null) {
			throw new PsPageNotFoundException;
		}
		
		return $escalationLevel;
	}

}

?>
